package com.gintama.base.enums;

import org.apache.commons.lang3.StringUtils;

/**
 * The enum Result code series.
 *
 * @author hao.hu
 * @since 2020 /3/19
 */
public enum ResultCodeSeries {

    /**
     * 参数异常
     */
    PARAM_ERROR("1"),
    /**
     * 业务异常
     */
    BUSINESS_ERROR("2"),
    /**
     * 程序异常
     */
    PROGRAM_ERROR("3"),
    /**
     * 网络异常
     */
    NETWORK_ERROR("4"),
    ;

    private static final int INDEX = 4;

    private final String value;

    ResultCodeSeries(String value) {
        this.value = value;
    }

    /**
     * Return the string value of this result code series. Ranges from 1 to 4.
     *
     * @return the string
     */
    public String value() {
        return this.value;
    }

    /**
     * Return the enum constant of this type with the corresponding series.
     *
     * @param status a standard result code enum value
     * @return the enum constant of this type with the corresponding series
     * @throws IllegalArgumentException if this enum has no corresponding constant
     */
    public static ResultCodeSeries value(BaseResultCode status) {
        return value(status.code());
    }

    /**
     * Return the enum constant of this type with the corresponding series.
     *
     * @param code the result code (potentially non-standard)
     * @return the enum constant of this type with the corresponding series
     * @throws IllegalArgumentException if this enum has no corresponding constant
     */
    public static ResultCodeSeries value(String code) {
        ResultCodeSeries series = resolve(code);
        if (series == null) {
            throw new IllegalArgumentException("No matching constant for [" + code + "]");
        }
        return series;
    }

    /**
     * Resolve the given status code to an {@code ResultCodeSeries}, if possible.
     *
     * @param code the result code status code (potentially non-standard)
     * @return the corresponding {@code ResultCodeSeries}, or {@code null} if not found
     */
    public static ResultCodeSeries resolve(String code) {
        if (StringUtils.isBlank(code) || code.length() < 4) {
            return null;
        }
        int beginIndex = code.length() - INDEX;
        String seriesCode = code.substring(beginIndex, beginIndex + 1);
        for (ResultCodeSeries series : values()) {
            if (series.value.equals(seriesCode)) {
                return series;
            }
        }
        return null;
    }

}
